<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--区域数据-->
        <pane size="16">
          <el-col>
            <div class="head-container" style="margin-bottom: 20px">
              <el-button icon="el-icon-plus" @click="handleAreaAdd">添加区域</el-button>
            </div>
            <div class="head-container">
              <el-input v-model="areaName" placeholder="请输入区域名称" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="areaOptions" :props="defaultProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current>
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span :class="data.type === 'area' ? 'node-area' : 'node-device'"
                    @click="data.type === 'area' ? handleNodeClick(data) : ''">{{ data.label }}</span>
                  <span class="tree-node-icons node-area" v-if="data.type === 'area'">
                    <!-- <el-popover placement="right" popper-class="custom-popover" trigger="click">
                      <div class="popover-content">
                        <el-button class="btn" type="text" @click="handleDevAdd(data)">添加设备</el-button>
                      </div>
                      <i class="el-icon-plus" slot="reference" />
                    </el-popover> -->
                    <i class="el-icon-plus" @click="() => handleDevAdd(data)" />
                  </span>
                  <span class="tree-node-icons node-device" v-if="data.type === 'device'">
                    <!-- <el-popover placement="right" popper-class="custom-popover" trigger="click">
                      <div class="popover-content">
                        <el-button class="btn" type="text" @click="handleDevUpdate(data)">修改设备</el-button>
                        <el-button class="btn" type="text" @click="handleDevDelete(data)">删除设备</el-button>
                      </div>
                      <i class="el-icon-setting" slot="reference" />
                    </el-popover> -->
                    <i class="el-icon-edit" @click="() => handleDevUpdate(data)" />
                    <i class="el-icon-delete" @click="() => handleDevDelete(data)" />
                  </span>
                </span>
              </el-tree>
            </div>
          </el-col>
        </pane>
        <!--视频列表数据-->
        <pane size="84">
          <el-col>
            <el-row :gutter="10" class="mb8">
              <el-row :gutter="10" class="mb8">
                <div class="top-right-btn" style="margin-right: 5px">
                  <el-row>
                    <el-button :class="[gridSize == 4 ? 'clk-btn' : 'dft-btn']" size="mini" ref="defaultBtn"
                      @click="setGrid(4)">四宫格</el-button>
                    <el-button :class="[gridSize == 9 ? 'clk-btn' : 'dft-btn']" size="mini"
                      @click="setGrid(9)">九宫格</el-button>
                    <el-button :class="[gridSize == 16 ? 'clk-btn' : 'dft-btn']" size="mini"
                      @click="setGrid(16)">十六宫格</el-button>
                  </el-row>
                </div>
              </el-row>
            </el-row>
            <el-row :gutter="20" class="video-grid">
              <el-col :span="getColSpan" v-for="(video, index) in deviceList" :key="video.id">
                <el-card shadow="hover" :class="getVideoCardClass">
                  <!-- 实时视频流 -->
                  <video :src="video.videoUrl" class="video-player" muted controls preload="metadata"></video>
                  <!-- 视频信息 -->
                  <div class="video-info">
                    <span :class="videoInfoClass(gridSize)">设备名称：{{ video.deviceName }}</span>
                    <span :class="videoInfoClass(gridSize)">定位信息：{{ video.position }}</span>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <pagination layout="prev, pager, next" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 添加或修改视频设备管理对话框 -->
    <el-dialog :title="devTitle" :visible.sync="devOpen" width="500px" append-to-body>
      <el-form ref="devForm" :model="devForm" :rules="devRules" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="devForm.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="定位信息" prop="position">
          <el-input v-model="devForm.position" placeholder="请输入定位信息" />
        </el-form-item>
        <el-form-item label="链接" prop="videoUrl">
          <el-input v-model="devForm.videoUrl" placeholder="请输入视频流链接" />
        </el-form-item>
        <!-- <el-form-item label="区域id" prop="areaId">
          <el-input v-model="devForm.areaId" placeholder="请输入区域id" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDevForm">确 定</el-button>
        <el-button @click="cancelDev">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改视频区域管理对话框 -->
    <el-dialog :title="areaTitle" :visible.sync="areaOpen" width="500px" append-to-body>
      <el-form ref="areaForm" :model="areaForm" :rules="areaRules" label-width="80px">
        <el-form-item label="区域" prop="area">
          <el-input v-model="areaForm.area" placeholder="请输入区域" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAreaForm">确 定</el-button>
        <el-button @click="cancelArea">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/video/device";
import { treeArea, delArea, addArea } from "@/api/video/area";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "VideoManage",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      devTitle: "",
      devOpen: false,
      areaTitle: "",
      areaOpen: false,
      areaName: undefined,
      // 设备表单参数
      devForm: {},
      // 设备表单校验
      devRules: {
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        position: [
          { required: true, message: "定位信息不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频流链接不能为空", trigger: "blur" }
        ],
      },
      // 区域表单参数
      areaForm: {},
      // 区域表单校验
      areaRules: {
        area: [
          { required: true, message: "区域不能为空", trigger: "blur" }
        ],
      },


      // 总条数
      total: 4,
      videos: [],
      gridSize: 4, // 当前布局，默认 4 宫格
      // 视频表格数据
      deviceList: [],
      // 所有部门树选项
      areaOptions: [
      ],
      // 过滤掉已禁用部门树选项
      enabledAreaOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        areaId: null,
        pageNum: 1,
        pageSize: 4,
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    areaName(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    getVideoCardClass() {
      return function (index) {
        return [`video-card-${this.gridSize}`];
      };
    },
    // 根据宫格数量计算列宽
    getColSpan() {
      if (this.gridSize === 4) return 12; // 四宫格
      if (this.gridSize === 9) return 8; // 九宫格
      if (this.gridSize === 16) return 6; // 十六宫格
    },
    videoInfoClass() {
      return function (index) {
        return [`video-info-${this.gridSize}`];
      };
    },
  },
  created() {
    this.getList();
    this.getAreaTree();
  },
  mounted() {
    this.$refs.defaultBtn.$el.click();
  },
  methods: {
    // 计算当前需要展示的视频
    visibleVideos(rows) {
      let videos = rows.concat();
      //this.queryParams.pageSize = this.gridSize;
      let len = videos.length;
      if (len < this.gridSize) {
        videos.push(...Array(this.gridSize - len).fill({}));
      } else if (len > this.gridSize) {
        videos.slice(0, this.gridSize);
      }
      this.deviceList = videos;
    },

    // 设置宫格布局
    setGrid(size) {
      this.gridSize = size;
      this.queryParams.pageSize = size;
      this.getList();
    },
    /** 查询视频列表 */
    getList() {
      if (this.areaOptions == null || this.areaOptions.length == 0) {
        return;
      }
      if (this.queryParams.areaId == null) {
        this.queryParams.areaId = this.areaOptions[0].id;
      }
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        //this.deviceList = response.rows;
        this.visibleVideos(response.rows);
        this.total = response.total;
        this.loading = false;
      });

    },
    /** 查询部门下拉树结构 */
    getAreaTree() {
      const params = {
        areaName: this.areaName,
      };
      treeArea(params).then((response) => {
        this.areaOptions = response.data;
        this.enabledAreaOptions = this.filterDisabledArea(
          JSON.parse(JSON.stringify(response.data))
        );
        if (this.areaOptions.length > 0) {
          this.queryParams.areaId = this.areaOptions[0].id;
          const queryParams = {
            areaId: this.areaOptions[0].id,
            pageNum: 1,
            pageSize: 4,
          };
          listDevice(queryParams).then(response => {
            //this.deviceList = response.rows;
            this.visibleVideos(response.rows);
            this.total = response.total;
          });
        }

      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.areaId = data.id;
      this.handleQuery();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 过滤禁用的部门
    filterDisabledArea(areaList) {
      return areaList.filter((area) => {
        if (area.disabled) {
          return false;
        }
        if (area.children && area.children.length) {
          area.children = this.filterDisabledArea(area.children);
        }
        return true;
      });
    },

    // 取消设备按钮
    cancelDev() {
      this.devOpen = false;
      this.resetDevForm();
    },
    // 设备表单重置
    resetDevForm() {
      this.devForm = {
        id: null,
        deviceName: null,
        position: null,
        videoUrl: null,
        areaId: null
      };
      this.resetForm("devForm");
    },

    /** 新增按钮操作 */
    handleDevAdd(data) {
      this.resetDevForm();
      this.devForm.areaId = data.id;
      this.devOpen = true;
      this.devTitle = "添加视频设备管理";
    },
    /** 修改按钮操作 */
    handleDevUpdate(data) {
      this.resetDevForm();
      const id = data.id || this.ids
      getDevice(id).then(response => {
        this.devForm = response.data;
        this.devOpen = true;
        this.devTitle = "修改设备管理";
      });
    },
    /** 提交按钮 */
    submitDevForm() {
      this.$refs["devForm"].validate(valid => {
        if (valid) {
          if (this.devForm.id != null) {
            updateDevice(this.devForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.devOpen = false;
              this.getAreaTree();
              this.getList();
            });
          } else {
            addDevice(this.devForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.devOpen = false;
              this.getAreaTree();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDevDelete(data) {
      const ids = data.id
      this.$modal.confirm('是否确认删除视频设备管理名称为"' + data.label + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getAreaTree();
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    // 取消按钮
    cancelArea() {
      this.areaOpen = false;
      this.resetArea();
    },
    // 表单重置
    resetArea() {
      this.areaForm = {
        id: null,
        area: null
      };
      this.resetForm("areaForm");
    },

    /** 新增按钮操作 */
    handleAreaAdd() {
      this.resetArea();
      this.areaOpen = true;
      this.areaTitle = "添加区域管理";
    },
    /** 提交按钮 */
    submitAreaForm() {
      this.$refs["areaForm"].validate(valid => {
        if (valid) {
          if (this.areaForm.id != null) {
            updateArea(this.areaForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.areaOpen = false;
              this.getAreaTree();
            });
          } else {
            addArea(this.areaForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.areaOpen = false;
              this.getAreaTree();
            });
          }
        }
      });
    },

  },
};
</script>

<style lang="scss">
/* 自定义 el-popover 样式 */
.el-popover.custom-popover {
  min-width: 80px !important;
}
</style>
<style lang="scss" scoped>
.node-device {
  font-size: small;
}

.node-area {
  font-size: small;
  font-weight: bold;
}

.tree-node-icons {
  margin-left: 10px;
  /* 调整图标与标签之间的距离 */
}

.tree-node-icons i {
  margin-right: 5px;
  /* 调整图标之间的距离 */
  color: #409EFF;
  /* 设置图标颜色 */
}

.btn {
  margin-left: 0px;
}

.popover-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 居中对齐 */
  justify-content: center;
  /* 居中对齐 */
}

.video-grid {
  display: flex;
  flex-wrap: wrap;
}

.el-card {
  margin-top: 10px;

}

::v-deep .el-card__body {
  padding: 5px;
}

.video-card-4 {
  padding: 5px 5px 1.5rem 5px;
  height: 50vh;
}

.video-card-9 {
  padding: 5px 5px 1.5rem 5px;
  height: 30vh;
}

.video-card-16 {
  padding: 5px 5px 1.5rem 5px;
  height: 20vh;
}

.video-player {
  width: 100%;
  aspect-ratio: 16/9;
  object-fit: cover;
  background-color: black;
}

.video-info {
  padding: 0.125rem 0.0625rem 0.125rem 0.0625rem;
  display: flex;
  flex-flow: row wrap;
  align-content: space-between;
  justify-content: space-between;
}


.video-info-4 {
  font-size: 0.8rem;
}

.video-info-9 {
  font-size: 0.75rem;
}

.video-info-16 {
  font-size: 0.64rem;
}

.dft-btn {
  position: relative;
  text-align: center;
}

.clk-btn {
  position: relative;
  background: #67c7ff;
  text-align: center;
}
</style>